package com.example.toycarcontroller



import android.Manifest

import android.annotation.SuppressLint

import android.app.Application

import android.bluetooth.*

import android.bluetooth.le.*

import android.content.Context

import android.content.Intent

import android.content.pm.PackageManager

import android.os.*

import android.util.Log

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import android.widget.*

import androidx.activity.result.contract.ActivityResultContracts

import androidx.appcompat.app.AlertDialog

import androidx.appcompat.app.AppCompatActivity

import androidx.core.app.ActivityCompat

import androidx.core.content.ContextCompat

import androidx.lifecycle.ViewModelProvider

import androidx.lifecycle.AndroidViewModel



class MainActivity : AppCompatActivity() {

    // 新增设备选择对话框变量

    private lateinit var deviceDialog: AlertDialog



    // 添加ViewModel

    private lateinit var sharedViewModel: SharedViewModel



    // Bluetooth相关变量

    private lateinit var bluetoothManager: BluetoothManager

    private lateinit var bluetoothAdapter: BluetoothAdapter

    private lateinit var bluetoothLeScanner: BluetoothLeScanner

    private var bluetoothGatt: BluetoothGatt? = null

    private var scanning = false



    // 新增蓝牙服务模块引用 === 解决 "Unresolved reference" 问题 ===

    private lateinit var bluetoothService: BluetoothService



    // 权限请求相关

    private val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

        mutableListOf(

            Manifest.permission.BLUETOOTH_SCAN,

            Manifest.permission.BLUETOOTH_CONNECT,

            Manifest.permission.ACCESS_FINE_LOCATION

        )

    } else {

        mutableListOf(

            Manifest.permission.BLUETOOTH,

            Manifest.permission.BLUETOOTH_ADMIN,

            Manifest.permission.ACCESS_FINE_LOCATION

        )

    }



    private fun checkPermissions(): Boolean {

        return permissions.all {

            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED

        }.also { result ->

            if (!result) {

                Log.d(TAG, "缺少以下权限: ${permissions.filter {

                    ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED

                }}")

            }

        }

    }



    private val requestPermissionLauncher = registerForActivityResult(

        ActivityResultContracts.RequestMultiplePermissions()

    ) { grants ->

        if (grants.all { it.value }) {

            // 修改为实际存在的初始化方法

            initBluetoothComponents()

        } else {

            Toast.makeText(this, "需要权限才能使用蓝牙功能", Toast.LENGTH_SHORT).show()

        }

    }





    // 其他组件

    private lateinit var deviceListAdapter: DeviceListAdapter

    private val handler = Handler(Looper.getMainLooper())

    private val TAG = "BluetoothController"



    // 连接超时时间（10秒）

    companion object {

        private const val CONNECTION_TIMEOUT = 10000L

    }



    private val connectionTimeoutHandler = Handler(Looper.getMainLooper())



    // 添加连接状态相关的成员变量

    private lateinit var tvConnectionStatus: TextView

    private lateinit var tvDeviceName: TextView



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        Log.d(TAG, "MainActivity onCreate")



        // 初始化蓝牙服务必须在其他操作之前

        bluetoothService = BluetoothService.getInstance(this)



        // 使用单例ViewModel

        sharedViewModel = SharedViewModel.getInstance(application as Application)



        // 记录初始ViewModel状态

        Log.d(TAG, "初始ViewModel状态: ${sharedViewModel.bluetoothStatus.value}")



        // 初始化连接状态显示组件

        tvConnectionStatus = findViewById(R.id.tv_connection_status)

        tvDeviceName = findViewById(R.id.tv_device_name)



        // 检查并请求权限

        if (!checkPermissions()) {

            requestPermissionLauncher.launch(permissions.toTypedArray())

            return

        }



        // 设置服务发现回调

        bluetoothService.setServiceDiscoveryCallback { services ->

            sharedViewModel.updateServices(services)

        }



        initBluetoothComponents()

        setupUI()

    }



    @SuppressLint("MissingPermission")

    private fun initBluetoothComponents() {

        bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager

        bluetoothAdapter = bluetoothManager.adapter ?: run {

            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show()

            finish()

            return

        }



        bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner

        deviceListAdapter = DeviceListAdapter(this)



        if (!bluetoothAdapter.isEnabled) {

            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)

            startActivityForResult(enableBtIntent, 1)

        }



        // 初始化蓝牙服务

        bluetoothService = BluetoothService.getInstance(this)

    }



    private fun setupUI() {
        // 修改蓝牙按钮点击事件
        findViewById<Button>(R.id.btn_bluetooth).setOnClickListener {
            if (checkPermissions()) {
                if (bluetoothService.isScanning) {
                    bluetoothService.stopScan()
                    findViewById<Button>(R.id.btn_bluetooth).text = "搜索蓝牙设备"
                } else {
                    startBleScan()
                    findViewById<Button>(R.id.btn_bluetooth).text = "停止扫描"
                }
            } else {
                requestPermissionLauncher.launch(permissions.toTypedArray())
            }
        }

        // 修改设备列表视图ID与布局文件保持一致
        val deviceListView = findViewById<ListView>(R.id.list_device).apply {
            adapter = deviceListAdapter
            onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                val device = deviceListAdapter.getItem(position) as BluetoothDevice
                Log.d(TAG, "选择连接设备: ${device.address}")
                bluetoothService.stopScan()
                bluetoothService.connectToDevice(device)
            }
        }

        // 修改模式一按钮点击事件，移除蓝牙连接检查

        findViewById<Button>(R.id.btn_mode1).setOnClickListener {

            val intent = Intent(this, DebugActivity::class.java)

            startActivity(intent)

        }



        // 设置蓝牙连接状态回调

        bluetoothService.setConnectionStateCallback { isConnected, deviceName ->

            runOnUiThread {

                updateUiConnectionStatus(isConnected, deviceName)

            }

        }

    }



    private fun startBleScan() {
        if (!bluetoothAdapter.isEnabled) {
            Toast.makeText(this, "请先启用蓝牙", Toast.LENGTH_SHORT).show()
            return
        }

        // 清空设备列表
        deviceListAdapter.clear()
        deviceListAdapter.notifyDataSetChanged()

        // 启动扫描 - 修改回调参数类型
        bluetoothService.startScan { device, rssi ->
            runOnUiThread {
                // 只添加有效设备
                if (device != null) {
                    deviceListAdapter.addDevice(device, rssi)
                    deviceListAdapter.notifyDataSetChanged()
                }
            }
        }

        // 修改：使用setScanCallback方法替代直接访问scanResultCallback
        bluetoothService.setScanCallback(object : ScanCallback() {
            override fun onScanFailed(errorCode: Int) {
                super.onScanFailed(errorCode)
                runOnUiThread {
                    findViewById<Button>(R.id.btn_bluetooth).text = "搜索蓝牙设备"
                    Toast.makeText(this@MainActivity, "扫描失败: $errorCode", Toast.LENGTH_SHORT).show()
                }
            }
        })
    }

    private fun recreateDialog(): AlertDialog {
        return AlertDialog.Builder(this)
            .setTitle("选择蓝牙设备")
            .setAdapter(deviceListAdapter) { _, which ->
                val device = deviceListAdapter.getItem(which) as BluetoothDevice
                Log.d(TAG, "选择连接设备: ${device.address}")
                bluetoothService.connectToDevice(device)
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                bluetoothService.stopScan()
            }
            .setOnDismissListener {
                bluetoothService.stopScan()
            }
            .setCancelable(false)
            .create()
    }

    private fun updateUiConnectionStatus(isConnected: Boolean, deviceName: String) {
        tvConnectionStatus.text = if (isConnected) "已连接" else "未连接"
        tvDeviceName.text = deviceName

        // 新增: 连接成功后隐藏设备列表并恢复按钮文本
        if (isConnected) {
            deviceListAdapter.clear()
            findViewById<ListView>(R.id.list_device).visibility = View.INVISIBLE
            findViewById<Button>(R.id.btn_bluetooth).text = "搜索蓝牙设备"
            bluetoothService.stopScan()
        } else {
            findViewById<ListView>(R.id.list_device).visibility = View.VISIBLE
        }

        // 更新ViewModel中的蓝牙状态

        sharedViewModel.updateStatus(isConnected, deviceName)

    }



    override fun onDestroy() {

        // 修改日志输出，使用BluetoothService的连接状态

        Log.d(TAG, "MainActivity onDestroy, 蓝牙状态: ${if (bluetoothService.isConnected) "已连接" else "未连接"}")



        // 移除所有回调

        bluetoothService.setConnectionStateCallback(null)



        super.onDestroy()

        handler.removeCallbacksAndMessages(null)

        connectionTimeoutHandler.removeCallbacksAndMessages(null)

    }



    // 设备列表适配器

    private inner class DeviceListAdapter(context: Context) : BaseAdapter() {

        private val devices = mutableListOf<BluetoothDevice>()

        private val rssiValues = mutableListOf<Int>()

        private val inflater = LayoutInflater.from(context)



        @SuppressLint("MissingPermission")

        fun addDevice(device: BluetoothDevice, rssi: Int) {
            if (device.address != "00:00:00:00:00:00") {  // 过滤掉无效设备
                if (!devices.any { it.address == device.address }) {
                    devices.add(device)
                    rssiValues.add(rssi)
                }
            }
        }



        fun clear() {

            devices.clear()

            rssiValues.clear()

        }



        override fun getCount() = devices.size

        override fun getItem(position: Int) = devices[position]

        override fun getItemId(position: Int) = position.toLong()



        @SuppressLint("MissingPermission")

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {

            val view = convertView ?: inflater.inflate(R.layout.list_item_device, parent, false)



            val device = devices[position]

            val rssi = rssiValues[position]



            view.findViewById<TextView>(R.id.deviceName).text = device.name ?: "未知设备"

            view.findViewById<TextView>(R.id.deviceInfo).text = "${device.address} (RSSI: $rssi)"



            // 统一连接处理逻辑

            var lastClickTime = 0L

            val connectHandler = View.OnClickListener {

                // 添加防抖动逻辑（500ms）

                if (SystemClock.elapsedRealtime() - lastClickTime < 500) {

                    return@OnClickListener

                }

                lastClickTime = SystemClock.elapsedRealtime()



                // 停止扫描并连接设备

                val activity = this@MainActivity

                activity.bluetoothService.stopScan()  // 替换为正确方法

                // 修改蓝牙服务模块的连接方法

                activity.bluetoothService.connectToDevice(device)



                // 关闭对话框

                (parent?.context as? AlertDialog)?.dismiss()

            }



            // 为按钮设置点击监听

            view.findViewById<Button>(R.id.btn_connect).setOnClickListener(connectHandler)



            // 修改设备名称点击事件（移除isClickable=false）

            view.findViewById<TextView>(R.id.deviceName).setOnClickListener(connectHandler)



            // 确保其他区域不可点击

            view.isClickable = false

            view.isFocusable = false

            view.findViewById<View>(R.id.deviceInfo).isClickable = false

            view.findViewById<View>(R.id.deviceInfo).isFocusable = false



            return view

        }

    }

}